package com.xinruke.hostels.reservation.user.service.impl;

import com.xinruke.hostels.common.constants.RedisConstants;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.exception.BizException;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.MhHuiyuan;
import com.xinruke.hostels.common.po.MhHuiyuanQinshu;
import com.xinruke.hostels.common.po.YwFangtairiqijilu;
import com.xinruke.hostels.common.util.CustomSecurity;
import com.xinruke.hostels.common.util.UUIDUtil;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.reservation.interfaces.api.ReservationApi;
import com.xinruke.hostels.reservation.user.interfaces.dto.ContactsAddInfoDto;
import com.xinruke.hostels.reservation.user.interfaces.dto.RegisterDTO;
import com.xinruke.hostels.reservation.user.mapper.MhHuiyuanMapper;
import com.xinruke.hostels.reservation.user.service.PersonalService;
import com.xinruke.hostels.reservation.user.service.RegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.weekend.Weekend;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.xinruke.hostels.common.util.CustomSecurity.encodeMobile;

/**
 * @ClassName RegisterServiceImpl
 * @CreateDate 2019/6/14
 * @Author FengXinQiang
 * @Version V1.0.0.0
 * @Decription 注册Service
 */
@Service
@Slf4j
public class RegisterServiceImpl implements RegisterService {

    @Resource
    MhHuiyuanMapper huiyuanMapper;

    @Resource
    ReservationApi reservationApi;

    @Resource(name = "commonRedisTemplate")
    RedisTemplate commonRedisTemplate;

    @Resource
    PersonalService personalService;

    /**
     * 会员注册
     *
     * @param registerDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO userRegister(RegisterDTO registerDTO) {
        ResultVO resultVO = ResultVO.fail();

        String redisLockKey = RedisConstants.HUIYUAN_ZHUCE_LOCK_KEY_PREFIX;
        try {
            String shenfenzhenghao = registerDTO.getShenfenzhenghao();
            shenfenzhenghao = CustomSecurity.encodeIDCard(shenfenzhenghao);

            //使用redis，根据酒店id对房间操作加锁
            redisLockKey = redisLockKey + shenfenzhenghao;
            boolean lockRet = commonRedisTemplate.opsForValue().setIfAbsent(redisLockKey, shenfenzhenghao);
            if (!lockRet) {
                log.error("系统繁忙，请重试");
                resultVO.setMessage("系统繁忙，请重试");
                return resultVO;
            }

            //验证身份证号是否重复
            QueryConditions andQueryConditions = new QueryConditions();
            andQueryConditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);

            QueryConditions orQueryConditions = new QueryConditions();
            orQueryConditions.addCondition("shenfenzhenghao", EConditionOperator.EQULS, shenfenzhenghao);
            orQueryConditions.addCondition("shoujihao", EConditionOperator.EQULS, encodeMobile(registerDTO.getShoujihao()));

            MyExample myExample = new MyExample(MhHuiyuan.class, andQueryConditions);
            Weekend weekend = myExample.createOrWeekend(MhHuiyuan.class, orQueryConditions);
            weekend.and(myExample.getOredCriteria().get(0));

            List<MhHuiyuan> huiyuanList = huiyuanMapper.selectByExample(weekend);
            if (!CollectionUtils.isEmpty(huiyuanList)) {
                resultVO.setMessage("请勿重复注册");
                return resultVO;
            }

            //注册，针对huiyuan中的密码、手机号、身份证号，做加密处理
            MhHuiyuan huiyuan = new MhHuiyuan();
            BeanUtils.copyProperties(registerDTO, huiyuan);
            huiyuan.setZhuangtai(MhHuiyuan.ZHUANGTAI_YOUXIAO);
            huiyuan.setRenzhengzhuangtai(MhHuiyuan.RENZHENGZHUANGTAI_WEIRENZHENG);
            huiyuan.setYan(UUIDUtil.getUUID());
            String password = CustomSecurity.createUserPassword(shenfenzhenghao, huiyuan.getYan(), huiyuan.getMima());
            huiyuan.setMima(password);
            huiyuan.setShenfenzhenghao(shenfenzhenghao);
            huiyuan.setShoujihao(encodeMobile(huiyuan.getShoujihao()));
            huiyuan.setChuangjianshijian(new Date());
            huiyuan.setGengxinshijian(new Date());
            huiyuan.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
            int ret = huiyuanMapper.insertSelective(huiyuan);
            if (ret > 0) {
                resultVO.setCode(ResultVO.SUCCESS);
                resultVO.setMessage("用户注册成功");
            }


            //初始化联系人，插入自己
            ContactsAddInfoDto contactsAddInfoDto = new ContactsAddInfoDto();
            BeanUtils.copyProperties(registerDTO, contactsAddInfoDto);
            contactsAddInfoDto.setHuiyuanId(huiyuan.getId());
            contactsAddInfoDto.setGuanxi(MhHuiyuanQinshu.GUANXI_ZIJI);
            contactsAddInfoDto.setZhengjianleixing(MhHuiyuanQinshu.ZHENGJIANLEIXING_SHENFENZHENG);
            personalService.addContacts(contactsAddInfoDto);

        } catch (Exception e) {
            log.error("注册失败，系统异常", e);
            throw new BizException("注册失败，系统异常");
        } finally {
            commonRedisTemplate.delete(redisLockKey);
        }
        return resultVO;
    }
}
